package com.suzhe.ymall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhe.ymall.system.pojo.SysRole;
import com.suzhe.ymall.system.mapper.SysRoleMapper;
import com.suzhe.ymall.system.pojo.SysRoleResource;
import com.suzhe.ymall.system.service.ISysRoleResourceService;
import com.suzhe.ymall.system.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author suzhe
 * @since 2019-06-07
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    ISysRoleResourceService iSysRoleResourceService;


    @Transactional
    @Override
    public void saveSysRole(SysRole sysRole) {
        Integer roleId = sysRole.getId();
        sysRole.setUpdateTime(new Date());
        if (roleId == null){
            save(sysRole);
        }else{
            updateById(sysRole);
            deleteOldRoleResource(roleId);
        }
        List<Integer> resourceIds = sysRole.getResourceIds();
        List<SysRoleResource> sysRoleResources = new ArrayList<>(resourceIds.size());
        if (!resourceIds.isEmpty()){
            resourceIds.forEach(item -> {
                SysRoleResource sysRoleResource = new SysRoleResource();
                sysRoleResource.setRoleId(sysRole.getId());
                sysRoleResource.setResourceId(item);
                sysRoleResources.add(sysRoleResource);
            });
        }
        iSysRoleResourceService.saveBatch(sysRoleResources);
    }


    public void  deleteOldRoleResource(Integer roleId){
        iSysRoleResourceService.remove(new QueryWrapper<SysRoleResource>().eq("role_id",roleId));
    }
}
